import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Question, Prisma } from '@prisma/client';

@Injectable()
export class QuestionsService {
  private readonly logger = new Logger(QuestionsService.name);

  constructor(private prisma: PrismaService) {}

  async question(questionWhereUniqueInput: Prisma.QuestionWhereUniqueInput): Promise<Question | null> {
    this.logger.debug(`查询题目: ${JSON.stringify(questionWhereUniqueInput)}`);
    const question = await this.prisma.question.findUnique({
      where: questionWhereUniqueInput,
      include: {
        exam: true,
        createdBy: true
      }
    });
    if (!question) {
      this.logger.warn(`题目未找到: ${JSON.stringify(questionWhereUniqueInput)}`);
    }
    return question;
  }

  async questions(params: {
    skip?: number;
    take?: number;
    cursor?: Prisma.QuestionWhereUniqueInput;
    where?: Prisma.QuestionWhereInput;
    orderBy?: Prisma.QuestionOrderByWithRelationInput;
  }): Promise<Question[]> {
    this.logger.debug(`查询题目列表: ${JSON.stringify(params)}`);
    const { skip, take, cursor, where, orderBy } = params;
    return this.prisma.question.findMany({
      skip,
      take,
      cursor,
      where,
      orderBy,
      include: {
        exam: true,
        createdBy: true
      }
    });
  }

  async createQuestion(data: Prisma.QuestionCreateInput): Promise<Question> {
    this.logger.log(`创建新题目: ${data.content}`);
    
    try {
      const { userId, ...restData } = data as any;
      const questionData = {
        ...restData,
        options: Array.isArray(data.options) ? JSON.stringify(data.options) : data.options,
        score: data.score ? Number(data.score) : 1.0
      };
      return await this.prisma.question.create({
        data: questionData,
        include: {
          exam: true,
          createdBy: true
        }
      });
    } catch (error) {
      this.logger.error(`创建题目失败: ${error.message}`);
      throw error;
    }
  }

  async updateQuestion(params: {
    where: Prisma.QuestionWhereUniqueInput;
    data: Prisma.QuestionUpdateInput;
  }): Promise<Question> {
    const { where, data } = params;
    this.logger.log(`更新题目 ID: ${where.id}`);
    try {
      const { id, createdAt, updatedAt, createdBy, exam, ...updateData } = data as any;
      return await this.prisma.question.update({
        where,
        data: {
          ...updateData,
          score: data.score ? Number(data.score) : undefined,
          options: data.options ? (Array.isArray(data.options) ? JSON.stringify(data.options) : data.options) : undefined
        },
        include: {
          exam: true,
          createdBy: true
        }
      });
    } catch (error) {
      this.logger.error(`更新题目失败: ${error.message}`);
      throw error;
    }
  }

  async deleteQuestion(where: Prisma.QuestionWhereUniqueInput): Promise<Question> {
    this.logger.log(`删除题目 ID: ${where.id}`);
    return this.prisma.question.delete({
      where,
    });
  }
}